﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpShare.Storage {
    public class StorageContainer : StorageItem, IStorageContainer {
        private IStorageLookup _parentChangedLookup;

        public StorageContainer(string name, IStorageContainer parent)
            : base(name, parent) {
            this.Contents = new StorageItemCollection();
            _parentChangedLookup = this.Contents.ChangeParent(this);
        }

        public StorageItemCollection Contents { get; private set; }

        protected virtual IStorageFile CreateFile(string name) {
            throw new StorageItemUnauthorizedException();
        }

        protected virtual IStorageContainer CreateContainer(string name) {
            throw new StorageItemUnauthorizedException();
        }

        protected virtual void OnAccessingContents() {

        }

        #region IStorageContainer Members

        IStorageLookup IStorageContainer.Contents {
            get {
                this.OnAccessingContents();
                return _parentChangedLookup;
            }
        }

        IStorageFile IStorageContainer.CreateFile(string name) {
            IStorageFile newFile = this.CreateFile(name);

            if (newFile == null) {
                return null;
            }

            this.Contents.Add(newFile);

            return this.Contents[name].DemandFile();
        }

        IStorageContainer IStorageContainer.CreateContainer(string name) {
            IStorageContainer newContainer = this.CreateContainer(name);

            if (newContainer == null) {
                return null;
            }

            this.Contents.Add(newContainer);

            return this.Contents[name].DemandContainer();
        }

        #endregion

        #region ICastable<IStorageProvider> Members

        IStorageProvider ICastable<IStorageProvider>.TryCast() {
            return null;
        }

        #endregion
    }
}
